package com.xiaomazi.sms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xiaomazi.common.utils.R;
import com.xiaomazi.sms.service.SmsService;
import com.xiaomazi.sms.utils.RandomUtil;
import com.xiaomazi.sms.utils.TxCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @program: llxy-parent
 * @description: 短信业务类
 * @author: 小马子
 * @create: 2023-02-27 21:46
 **/
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 发送短信验证码
     * @param phone 手机号
     * @return code
     */
    @Override
    public R sendPhone(String phone) {
        if (StrUtil.isNotBlank(redisTemplate.opsForValue().get(phone))){
            return R.ok();
        }
        String fourBitRandom = RandomUtil.getFourBitRandom();
        boolean success = TxCode.SendCode(phone,fourBitRandom);
        if (success){
            redisTemplate.opsForValue().set(phone,fourBitRandom,5, TimeUnit.MINUTES);
            return R.ok();
        }
        return R.error().message("短信发送失败");
    }
}
